{% extends 'base.html' %}

{% block title %}{{ consumable.name }} - 耗材记录管理 - 固定资产管理系统{% endblock %}

{% block content %}
<div class="row">
    <div class="col-md-12">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="{% url 'assets:index' %}">首页</a></li>
                <li class="breadcrumb-item"><a href="{% url 'assets:consumable_list' %}">耗材管理</a></li>
                <li class="breadcrumb-item active" aria-current="page">{{ consumable.name }}</li>
            </ol>
        </nav>
        
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h2><i class="fas fa-box me-2"></i>{{ consumable.name }} - 耗材记录管理</h2>
            <div class="btn-group">
                <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#stockInModal">
                    <i class="fas fa-arrow-down me-1"></i>入库
                </button>
                <button type="button" class="btn btn-warning" data-bs-toggle="modal" data-bs-target="#stockOutModal">
                    <i class="fas fa-arrow-up me-1"></i>出库
                </button>
                <a href="{% url 'assets:consumable_update' consumable.pk %}" class="btn btn-primary">
                    <i class="fas fa-edit me-1"></i>编辑
                </a>
                <button type="button" class="btn btn-outline-primary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown">
                    <span class="visually-hidden">更多操作</span>
                </button>
                <ul class="dropdown-menu">
                    <li><a class="dropdown-item" href="#" onclick="exportRecords()">
                        <i class="fas fa-download me-2"></i>导出记录
                    </a></li>
                    <li><a class="dropdown-item" href="{% url 'assets:inventory_log_list' %}?search={{ consumable.name }}">
                        <i class="fas fa-history me-2"></i>查看全部记录
                    </a></li>
                    <li><a class="dropdown-item" href="#" onclick="printLabel()">
                        <i class="fas fa-print me-2"></i>打印标签
                    </a></li>
                    <li><hr class="dropdown-divider"></li>
                    <li><a class="dropdown-item" href="{% url 'assets:consumable_list' %}">
                        <i class="fas fa-arrow-left me-2"></i>返回列表
                    </a></li>
                    <li><hr class="dropdown-divider"></li>
                    <li><a class="dropdown-item text-danger" href="{% url 'assets:consumable_delete' consumable.pk %}" onclick="return confirm('确定要删除耗材 {{ consumable.name }} 吗？')">
                        <i class="fas fa-trash me-2"></i>删除耗材
                    </a></li>
                </ul>
            </div>
        </div>

        <div class="row">
            <!-- 基本信息 -->
            <div class="col-md-8">
                <!-- 耗材基本信息 -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-info-circle me-2"></i>耗材基本信息
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <table class="table table-borderless">
                                    <tr>
                                        <td width="30%" class="text-muted">耗材名称:</td>
                                        <td><strong>{{ consumable.name }}</strong></td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">耗材编码:</td>
                                        <td><code>{{ consumable.code }}</code></td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">型号规格:</td>
                                        <td>
                                            {% if consumable.model %}
                                                <span class="badge bg-secondary">{{ consumable.model }}</span>
                                            {% else %}
                                                <span class="text-muted">-</span>
                                            {% endif %}
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">类别:</td>
                                        <td>
                                            {% if consumable.category %}
                                                <span class="badge bg-info">{{ consumable.category.name }}</span>
                                            {% else %}
                                                <span class="text-muted">-</span>
                                            {% endif %}
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">计量单位:</td>
                                        <td><span class="badge bg-light text-dark">{{ consumable.unit }}</span></td>
                                    </tr>
                                </table>
                            </div>
                            <div class="col-md-6">
                                <table class="table table-borderless">
                                    <tr>
                                        <td width="30%" class="text-muted">存储仓库:</td>
                                        <td>
                                            {% if consumable.warehouse %}
                                                <div class="d-flex align-items-center">
                                                    <i class="fas fa-warehouse me-1 text-success"></i>
                                                    <a href="{% url 'assets:warehouse_detail' consumable.warehouse.pk %}" class="text-decoration-none">{{ consumable.warehouse.name }}</a>
                                                </div>
                                            {% else %}
                                                <span class="text-muted">-</span>
                                            {% endif %}
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">存储位置:</td>
                                        <td>
                                            {% if consumable.location %}
                                                <i class="fas fa-map-marker-alt me-1 text-info"></i>{{ consumable.location }}
                                            {% else %}
                                                <span class="text-muted">-</span>
                                            {% endif %}
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">采购单价:</td>
                                        <td>
                                            <span class="text-success fw-bold">¥{{ consumable.purchase_price|floatformat:2 }}</span>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">供应商:</td>
                                        <td>
                                            {% if consumable.supplier %}
                                                <div class="d-flex align-items-center">
                                                    <i class="fas fa-truck me-1 text-info"></i>
                                                    <a href="{% url 'assets:supplier_detail' consumable.supplier.pk %}" class="text-decoration-none">{{ consumable.supplier.name }}</a>
                                                </div>
                                            {% else %}
                                                <span class="text-muted">-</span>
                                            {% endif %}
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">创建时间:</td>
                                        <td>
                                            <i class="fas fa-calendar-plus me-1 text-primary"></i>{{ consumable.created_at|date:"Y-m-d H:i" }}
                                        </td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                        
                        {% if consumable.description %}
                        <div class="mt-3">
                            <h6 class="text-muted">
                                <i class="fas fa-file-alt me-2"></i>耗材描述:
                            </h6>
                            <div class="alert alert-light">
                                <p class="mb-0">{{ consumable.description }}</p>
                            </div>
                        </div>
                        {% endif %}
                    </div>
                </div>
                
                <!-- 库存状态实时展示 -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-chart-line me-2"></i>库存状态实时展示
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <table class="table table-borderless">
                                    <tr>
                                        <td width="30%" class="text-muted">当前库存:</td>
                                        <td>
                                            {% if consumable.quantity <= 0 %}
                                                <span class="badge bg-dark fs-6">{{ consumable.quantity }} {{ consumable.unit }}</span>
                                                <small class="text-dark ms-2">缺货</small>
                                            {% elif consumable.quantity <= consumable.min_quantity %}
                                                <span class="badge bg-danger fs-6">{{ consumable.quantity }} {{ consumable.unit }}</span>
                                                <small class="text-danger ms-2">库存不足</small>
                                            {% elif consumable.quantity <= consumable.min_quantity|add:10 %}
                                                <span class="badge bg-warning fs-6">{{ consumable.quantity }} {{ consumable.unit }}</span>
                                                <small class="text-warning ms-2">库存偏低</small>
                                            {% else %}
                                                <span class="badge bg-success fs-6">{{ consumable.quantity }} {{ consumable.unit }}</span>
                                                <small class="text-success ms-2">库存正常</small>
                                            {% endif %}
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">最低库存:</td>
                                        <td>
                                            <span class="text-info fw-bold">{{ consumable.min_quantity }} {{ consumable.unit }}</span>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">库存价值:</td>
                                        <td>
                                            <span class="text-success fw-bold">¥{{ consumable.quantity|mul:consumable.purchase_price|floatformat:2 }}</span>
                                        </td>
                                    </tr>
                                </table>
                            </div>
                            <div class="col-md-6">
                                <table class="table table-borderless">
                                    <tr>
                                        <td width="30%" class="text-muted">库存周转:</td>
                                        <td>
                                            {% if total_out_quantity > 0 %}
                                                <span class="text-primary fw-bold">{{ total_out_quantity }} {{ consumable.unit }}</span>
                                                <small class="text-muted ms-1">(本月)</small>
                                            {% else %}
                                                <span class="text-muted">暂无数据</span>
                                            {% endif %}
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">最后入库:</td>
                                        <td>
                                            {% if last_in_log %}
                                                <i class="fas fa-arrow-down me-1 text-success"></i>{{ last_in_log.created_at|date:"m-d H:i" }}
                                            {% else %}
                                                <span class="text-muted">暂无记录</span>
                                            {% endif %}
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">最后出库:</td>
                                        <td>
                                            {% if last_out_log %}
                                                <i class="fas fa-arrow-up me-1 text-danger"></i>{{ last_out_log.created_at|date:"m-d H:i" }}
                                            {% else %}
                                                <span class="text-muted">暂无记录</span>
                                            {% endif %}
                                        </td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                        
                        <!-- 库存状态进度条 -->
                        <div class="mt-3">
                            <h6 class="text-muted mb-2">库存状态指示</h6>
                            {% with stock_percentage=consumable.quantity|div:consumable.min_quantity|mul:100 %}
                            <div class="progress mb-2" style="height: 25px;">
                                {% if stock_percentage <= 0 %}
                                    <div class="progress-bar bg-dark" role="progressbar" style="width: 5%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
                                        缺货
                                    </div>
                                {% elif stock_percentage <= 100 %}
                                    <div class="progress-bar bg-danger" role="progressbar" style="width: {{ stock_percentage }}%" aria-valuenow="{{ stock_percentage }}" aria-valuemin="0" aria-valuemax="100">
                                        {{ stock_percentage|floatformat:0 }}%
                                    </div>
                                {% elif stock_percentage <= 150 %}
                                    <div class="progress-bar bg-warning" role="progressbar" style="width: 100%" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100">
                                        库存偏低
                                    </div>
                                {% else %}
                                    <div class="progress-bar bg-success" role="progressbar" style="width: 100%" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100">
                                        库存充足
                                    </div>
                                {% endif %}
                            </div>
                            {% endwith %}
                            <div class="d-flex justify-content-between">
                                <small class="text-muted">0</small>
                                <small class="text-muted">最低库存线: {{ consumable.min_quantity }}</small>
                                <small class="text-muted">当前: {{ consumable.quantity }}</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 侧边栏信息 -->
            <div class="col-md-4">
                <!-- 库存状态概览 -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-chart-pie me-2"></i>库存状态概览
                        </h5>
                    </div>
                    <div class="card-body text-center">
                        <div class="mb-3">
                            {% if consumable.quantity <= 0 %}
                                <div class="alert alert-dark">
                                    <i class="fas fa-exclamation-triangle fa-2x mb-2"></i>
                                    <h5>缺货警告</h5>
                                    <p class="mb-0">当前库存为0，需要紧急补货</p>
                                </div>
                            {% elif consumable.quantity <= consumable.min_quantity %}
                                <div class="alert alert-danger">
                                    <i class="fas fa-exclamation-triangle fa-2x mb-2"></i>
                                    <h5>库存不足</h5>
                                    <p class="mb-0">当前库存低于最低库存线</p>
                                </div>
                            {% elif consumable.quantity <= consumable.min_quantity|add:10 %}
                                <div class="alert alert-warning">
                                    <i class="fas fa-exclamation-circle fa-2x mb-2"></i>
                                    <h5>库存偏低</h5>
                                    <p class="mb-0">建议及时补货</p>
                                </div>
                            {% else %}
                                <div class="alert alert-success">
                                    <i class="fas fa-check-circle fa-2x mb-2"></i>
                                    <h5>库存正常</h5>
                                    <p class="mb-0">当前库存充足</p>
                                </div>
                            {% endif %}
                        </div>
                        
                        <div class="row text-center">
                            <div class="col-6">
                                <h4 class="text-primary">{{ consumable.quantity }}</h4>
                                <small class="text-muted">当前库存</small>
                            </div>
                            <div class="col-6">
                                <h4 class="text-info">{{ consumable.min_quantity }}</h4>
                                <small class="text-muted">最低库存</small>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 快速操作 -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-bolt me-2"></i>快速操作
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="d-grid gap-2">
                            <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#stockInModal">
                                <i class="fas fa-arrow-down me-2"></i>入库操作
                            </button>
                            <button type="button" class="btn btn-warning" data-bs-toggle="modal" data-bs-target="#stockOutModal">
                                <i class="fas fa-arrow-up me-2"></i>出库操作
                            </button>
                            <hr class="my-2">
                            <a href="{% url 'assets:consumable_update' consumable.pk %}" class="btn btn-outline-primary btn-sm">
                                <i class="fas fa-edit me-2"></i>编辑信息
                            </a>
                            <button type="button" class="btn btn-outline-info btn-sm" onclick="exportRecords()">
                                <i class="fas fa-download me-2"></i>导出记录
                            </button>
                            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="printLabel()">
                                <i class="fas fa-print me-2"></i>打印标签
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- 统计信息 -->
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-chart-bar me-2"></i>统计信息
                        </h5>
                    </div>
                    <div class="card-body">
                        <table class="table table-borderless table-sm">
                            <tr>
                                <td class="text-muted">总入库次数:</td>
                                <td>
                                    <span class="text-success fw-bold">{{ total_in_count|default:0 }}</span>
                                </td>
                            </tr>
                            <tr>
                                <td class="text-muted">总出库次数:</td>
                                <td>
                                    <span class="text-danger fw-bold">{{ total_out_count|default:0 }}</span>
                                </td>
                            </tr>
                            <tr>
                                <td class="text-muted">本月入库:</td>
                                <td>
                                    <span class="text-success">{{ month_in_quantity|default:0 }} {{ consumable.unit }}</span>
                                </td>
                            </tr>
                            <tr>
                                <td class="text-muted">本月出库:</td>
                                <td>
                                    <span class="text-danger">{{ month_out_quantity|default:0 }} {{ consumable.unit }}</span>
                                </td>
                            </tr>
                            <tr>
                                <td class="text-muted">库存周转率:</td>
                                <td>
                                    {% if turnover_rate %}
                                        <span class="text-info fw-bold">{{ turnover_rate|floatformat:1 }}%</span>
                                    {% else %}
                                        <span class="text-muted">-</span>
                                    {% endif %}
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- 入库/出库记录管理 -->
        <div class="card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="fas fa-history me-2"></i>入库/出库记录管理
                </h5>
                <div class="btn-group btn-group-sm">
                    <button type="button" class="btn btn-outline-success" data-bs-toggle="modal" data-bs-target="#stockInModal">
                        <i class="fas fa-arrow-down me-1"></i>入库
                    </button>
                    <button type="button" class="btn btn-outline-warning" data-bs-toggle="modal" data-bs-target="#stockOutModal">
                        <i class="fas fa-arrow-up me-1"></i>出库
                    </button>
                    <a href="{% url 'assets:inventory_log_list' %}?search={{ consumable.name }}" class="btn btn-outline-primary">
                        查看全部记录
                    </a>
                </div>
            </div>
            <div class="card-body">
                {% if recent_logs %}
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead class="table-light">
                                <tr>
                                    <th width="12%">操作类型</th>
                                    <th width="15%">数量变化</th>
                                    <th width="12%">操作人</th>
                                    <th width="25%">操作描述</th>
                                    <th width="15%">操作时间</th>
                                    <th width="12%">库存余额</th>
                                    <th width="9%">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for log in recent_logs %}
                                <tr>
                                    <td>
                                        {% if log.transaction_type == 'in' %}
                                            <span class="badge bg-success">
                                                <i class="fas fa-arrow-down me-1"></i>入库
                                            </span>
                                        {% elif log.transaction_type == 'out' %}
                                            <span class="badge bg-danger">
                                                <i class="fas fa-arrow-up me-1"></i>出库
                                            </span>
                                        {% else %}
                                            <span class="badge bg-info">
                                                <i class="fas fa-exchange-alt me-1"></i>调整
                                            </span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            {% if log.transaction_type == 'in' %}
                                                <span class="text-success fw-bold">+{{ log.quantity }}</span>
                                            {% elif log.transaction_type == 'out' %}
                                                <span class="text-danger fw-bold">-{{ log.quantity }}</span>
                                            {% else %}
                                                <span class="text-info fw-bold">{{ log.quantity }}</span>
                                            {% endif %}
                                            <small class="text-muted ms-1">{{ consumable.unit }}</small>
                                        </div>
                                    </td>
                                    <td>
                                        {% if log.operator %}
                                            <div class="d-flex align-items-center">
                                                <i class="fas fa-user me-1 text-info"></i>
                                                {{ log.operator.get_full_name|default:log.operator.username }}
                                            </div>
                                        {% else %}
                                            <span class="text-muted">
                                                <i class="fas fa-robot me-1"></i>系统
                                            </span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if log.description %}
                                            <span title="{{ log.description }}">{{ log.description|truncatechars:35 }}</span>
                                        {% else %}
                                            <span class="text-muted">-</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        <div class="text-nowrap">
                                            <i class="fas fa-clock me-1 text-muted"></i>
                                            {{ log.created_at|date:"m-d H:i" }}
                                        </div>
                                        <small class="text-muted">{{ log.created_at|date:"Y" }}</small>
                                    </td>
                                    <td>
                                        <span class="badge bg-light text-dark">{{ log.remaining_quantity|default:"-" }}</span>
                                    </td>
                                    <td>
                                        <div class="btn-group btn-group-sm">
                                            <button type="button" class="btn btn-outline-info" title="查看详情" onclick="showLogDetail({{ log.pk }})">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                            {% if log.operator == request.user %}
                                            <button type="button" class="btn btn-outline-danger" title="删除记录" onclick="deleteLog({{ log.pk }})">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                            {% endif %}
                                        </div>
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- 记录统计 -->
                    <div class="mt-3">
                        <div class="row text-center">
                            <div class="col-md-3">
                                <div class="card bg-light">
                                    <div class="card-body py-2">
                                        <h6 class="text-success mb-0">{{ total_in_quantity|default:0 }}</h6>
                                        <small class="text-muted">总入库量</small>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="card bg-light">
                                    <div class="card-body py-2">
                                        <h6 class="text-danger mb-0">{{ total_out_quantity|default:0 }}</h6>
                                        <small class="text-muted">总出库量</small>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="card bg-light">
                                    <div class="card-body py-2">
                                        <h6 class="text-primary mb-0">{{ total_in_count|default:0 }}</h6>
                                        <small class="text-muted">入库次数</small>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="card bg-light">
                                    <div class="card-body py-2">
                                        <h6 class="text-warning mb-0">{{ total_out_count|default:0 }}</h6>
                                        <small class="text-muted">出库次数</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                {% else %}
                    <div class="text-muted text-center py-4">
                        <i class="fas fa-history fa-3x mb-3"></i>
                        <h6>暂无库存记录</h6>
                        <p class="mb-3">开始记录耗材的入库和出库操作</p>
                        <div class="btn-group">
                            <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#stockInModal">
                                <i class="fas fa-arrow-down me-2"></i>第一次入库
                            </button>
                            <button type="button" class="btn btn-warning" data-bs-toggle="modal" data-bs-target="#stockOutModal">
                                <i class="fas fa-arrow-up me-2"></i>第一次出库
                            </button>
                        </div>
                    </div>
                {% endif %}
            </div>
        </div>
        
        <!-- 操作历史记录 -->
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fas fa-clipboard-list me-2"></i>操作历史记录
                    <button type="button" class="btn btn-outline-info btn-sm float-end" onclick="exportRecords()">
                        <i class="fas fa-download me-1"></i>导出记录
                    </button>
                </h5>
            </div>
            <div class="card-body">
                {% if operation_logs %}
                    <div class="timeline">
                        {% for log in operation_logs %}
                        <div class="timeline-item mb-3">
                            <div class="d-flex">
                                <div class="timeline-marker me-3">
                                    {% if log.operation_type == 'create' %}
                                        <i class="fas fa-plus text-success"></i>
                                    {% elif log.operation_type == 'update' %}
                                        <i class="fas fa-edit text-primary"></i>
                                    {% elif log.operation_type == 'stock_in' %}
                                        <i class="fas fa-arrow-down text-success"></i>
                                    {% elif log.operation_type == 'stock_out' %}
                                        <i class="fas fa-arrow-up text-danger"></i>
                                    {% else %}
                                        <i class="fas fa-info text-info"></i>
                                    {% endif %}
                                </div>
                                <div class="timeline-content flex-grow-1">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div>
                                            <h6 class="mb-1">{{ log.get_operation_type_display }}</h6>
                                            <p class="text-muted mb-1">{{ log.description|default:"无描述" }}</p>
                                            <small class="text-muted">
                                                <i class="fas fa-user me-1"></i>{{ log.operator.get_full_name|default:log.operator.username }}
                                                <i class="fas fa-clock ms-2 me-1"></i>{{ log.created_at|date:"Y-m-d H:i" }}
                                            </small>
                                        </div>
                                        {% if log.quantity %}
                                        <div class="text-end">
                                            <span class="badge bg-light text-dark">{{ log.quantity }} {{ consumable.unit }}</span>
                                        </div>
                                        {% endif %}
                                    </div>
                                </div>
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                {% else %}
                    <div class="text-muted text-center py-3">
                        <i class="fas fa-clipboard-list fa-2x mb-2"></i>
                        <p class="mb-0">暂无操作历史记录</p>
                    </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<!-- 入库模态框 -->
<div class="modal fade" id="stockInModal" tabindex="-1" aria-labelledby="stockInModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="stockInModalLabel">
                    <i class="fas fa-arrow-down me-2 text-success"></i>耗材入库
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="stockInForm" method="post">
                <div class="modal-body">
                    {% csrf_token %}
                    <input type="hidden" name="transaction_type" value="in">
                    <input type="hidden" name="consumable_id" value="{{ consumable.pk }}">
                    
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle me-2"></i>
                        <strong>{{ consumable.name }}</strong> - 当前库存: <span class="fw-bold">{{ consumable.quantity }} {{ consumable.unit }}</span>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="inQuantity" class="form-label">入库数量 <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <input type="number" class="form-control" id="inQuantity" name="quantity" step="0.01" min="0.01" required>
                                    <span class="input-group-text">{{ consumable.unit }}</span>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="inBatchNumber" class="form-label">批次号</label>
                                <input type="text" class="form-control" id="inBatchNumber" name="batch_number" placeholder="可选">
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="inSupplier" class="form-label">供应商</label>
                                <select class="form-select" id="inSupplier" name="supplier_id">
                                    <option value="">选择供应商</option>
                                    {% for supplier in suppliers %}
                                    <option value="{{ supplier.pk }}" {% if supplier.pk == consumable.supplier.pk %}selected{% endif %}>{{ supplier.name }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="inUnitPrice" class="form-label">入库单价</label>
                                <div class="input-group">
                                    <span class="input-group-text">¥</span>
                                    <input type="number" class="form-control" id="inUnitPrice" name="unit_price" step="0.01" min="0" value="{{ consumable.purchase_price }}">
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="inDescription" class="form-label">入库说明</label>
                        <textarea class="form-control" id="inDescription" name="description" rows="3" placeholder="请输入入库原因或备注信息..."></textarea>
                    </div>
                    
                    <div class="alert alert-success">
                        <i class="fas fa-calculator me-2"></i>
                        入库后库存: <span id="afterInStock" class="fw-bold">{{ consumable.quantity }}</span> {{ consumable.unit }}
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-success">
                        <i class="fas fa-arrow-down me-1"></i>确认入库
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 出库模态框 -->
<div class="modal fade" id="stockOutModal" tabindex="-1" aria-labelledby="stockOutModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="stockOutModalLabel">
                    <i class="fas fa-arrow-up me-2 text-warning"></i>耗材出库
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="stockOutForm" method="post">
                <div class="modal-body">
                    {% csrf_token %}
                    <input type="hidden" name="transaction_type" value="out">
                    <input type="hidden" name="consumable_id" value="{{ consumable.pk }}">
                    
                    <div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        <strong>{{ consumable.name }}</strong> - 当前库存: <span class="fw-bold">{{ consumable.quantity }} {{ consumable.unit }}</span>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="outQuantity" class="form-label">出库数量 <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <input type="number" class="form-control" id="outQuantity" name="quantity" step="0.01" min="0.01" max="{{ consumable.quantity }}" required>
                                    <span class="input-group-text">{{ consumable.unit }}</span>
                                </div>
                                <div class="form-text">最大可出库: {{ consumable.quantity }} {{ consumable.unit }}</div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="outDepartment" class="form-label">领用部门</label>
                                <select class="form-select" id="outDepartment" name="department_id">
                                    <option value="">选择部门</option>
                                    {% for department in departments %}
                                    <option value="{{ department.pk }}">{{ department.name }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="outUser" class="form-label">领用人</label>
                                <select class="form-select" id="outUser" name="recipient_id">
                                    <option value="">选择领用人</option>
                                    {% for user in users %}
                                    <option value="{{ user.pk }}">{{ user.get_full_name|default:user.username }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="outPurpose" class="form-label">用途</label>
                                <select class="form-select" id="outPurpose" name="purpose">
                                    <option value="">选择用途</option>
                                    <option value="production">生产使用</option>
                                    <option value="maintenance">维修保养</option>
                                    <option value="office">办公使用</option>
                                    <option value="research">研发测试</option>
                                    <option value="other">其他</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="outDescription" class="form-label">出库说明</label>
                        <textarea class="form-control" id="outDescription" name="description" rows="3" placeholder="请输入出库原因或用途说明..."></textarea>
                    </div>
                    
                    <div class="alert alert-info">
                        <i class="fas fa-calculator me-2"></i>
                        出库后库存: <span id="afterOutStock" class="fw-bold">{{ consumable.quantity }}</span> {{ consumable.unit }}
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-warning">
                        <i class="fas fa-arrow-up me-1"></i>确认出库
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// 当前库存数量
const currentStock = {{ consumable.quantity }};

// 入库数量变化时更新预计库存
document.getElementById('inQuantity').addEventListener('input', function() {
    const inQuantity = parseFloat(this.value) || 0;
    const afterStock = currentStock + inQuantity;
    document.getElementById('afterInStock').textContent = afterStock.toFixed(2);
});

// 出库数量变化时更新预计库存
document.getElementById('outQuantity').addEventListener('input', function() {
    const outQuantity = parseFloat(this.value) || 0;
    const afterStock = Math.max(0, currentStock - outQuantity);
    document.getElementById('afterOutStock').textContent = afterStock.toFixed(2);
    
    // 检查是否超出库存
    if (outQuantity > currentStock) {
        this.classList.add('is-invalid');
        this.nextElementSibling.nextElementSibling.textContent = '出库数量不能超过当前库存';
        this.nextElementSibling.nextElementSibling.classList.add('text-danger');
    } else {
        this.classList.remove('is-invalid');
        this.nextElementSibling.nextElementSibling.textContent = `最大可出库: ${currentStock} {{ consumable.unit }}`;
        this.nextElementSibling.nextElementSibling.classList.remove('text-danger');
    }
});

// 入库表单提交
document.getElementById('stockInForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    
    fetch('/assets/consumable/{{ consumable.pk }}/stock-in/', {
        method: 'POST',
        body: formData,
        headers: {
            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
        },
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert('入库失败：' + data.error);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('入库失败，请重试');
    });
});

// 出库表单提交
document.getElementById('stockOutForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const outQuantity = parseFloat(document.getElementById('outQuantity').value);
    if (outQuantity > currentStock) {
        alert('出库数量不能超过当前库存');
        return;
    }
    
    const formData = new FormData(this);
    
    fetch('/assets/consumable/{{ consumable.pk }}/stock-out/', {
        method: 'POST',
        body: formData,
        headers: {
            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
        },
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert('出库失败：' + data.error);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('出库失败，请重试');
    });
});

// 导出记录
function exportRecords() {
    window.open(`/assets/consumable/{{ consumable.pk }}/export-records/`, '_blank');
}

// 打印标签
function printLabel() {
    window.open(`/assets/consumable/{{ consumable.pk }}/print-label/`, '_blank');
}

// 显示记录详情
function showLogDetail(logId) {
    fetch(`/assets/inventory-log/${logId}/detail/`)
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 显示详情模态框或弹窗
            alert(`记录详情:\n类型: ${data.log.transaction_type}\n数量: ${data.log.quantity}\n操作人: ${data.log.operator}\n时间: ${data.log.created_at}\n描述: ${data.log.description || '无'}`);
        } else {
            alert('获取记录详情失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('获取记录详情失败');
    });
}

// 删除记录
function deleteLog(logId) {
    if (confirm('确定要删除这条记录吗？此操作不可撤销！')) {
        fetch(`/assets/inventory-log/${logId}/delete/`, {
            method: 'POST',
            headers: {
                'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
                'Content-Type': 'application/json',
            },
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                location.reload();
            } else {
                alert('删除失败：' + data.error);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('删除失败，请重试');
        });
    }
}

// 部门选择变化时更新用户列表
document.getElementById('outDepartment').addEventListener('change', function() {
    const departmentId = this.value;
    const userSelect = document.getElementById('outUser');
    
    if (departmentId) {
        fetch(`/assets/department/${departmentId}/users/`)
        .then(response => response.json())
        .then(data => {
            userSelect.innerHTML = '<option value="">选择领用人</option>';
            data.users.forEach(user => {
                const option = document.createElement('option');
                option.value = user.id;
                option.textContent = user.name;
                userSelect.appendChild(option);
            });
        })
        .catch(error => {
            console.error('Error:', error);
        });
    } else {
        userSelect.innerHTML = '<option value="">选择领用人</option>';
    }
});
</script>
{% endblock %}